package com.goldcn.common;

import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.util.UuidUtils;
import com.goldcn.config.ProConstants;
import com.goldcn.enumeration.ErrorCodeEnum;
import com.goldcn.interceptor.SystemContext;
import com.goldcn.order.erpVo.ResultData;
import flexjson.JSONDeserializer;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.apache.commons.codec.Charsets;
import org.apache.log4j.Logger;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/9/1.
 */
public class CommonTools {

    private static final String ErrorCode="ERROR_GOODS_";

    public static Logger logger = Logger.getLogger(CommonTools.class);

    public static String getGUID() {
        return UuidUtils.uuid();
    }


    public static ServiceException createException(ErrorCodeEnum errorCodeEnum) {
        return new ServiceException(errorCodeEnum.getErrorMsg(),
                ErrorCode + errorCodeEnum.getErrorCode());
    }

    public static ServiceException createException(ErrorCodeEnum errorCodeEnum, String info) {
        return new ServiceException(errorCodeEnum.getErrorMsg()+":"+info,
                ErrorCode + errorCodeEnum.getErrorCode());
    }

    public static boolean isEmpty(String str) {
        boolean temp = true;
        if (null != str && !"".equals(str) && !"".equals(str.trim())
                && !"null".equals(str.trim())) {
            temp = false;
        }
        return temp;
    }

    public static boolean isEmpty(String[] str) {
        boolean temp = true;
        for (String s : str) {
            temp = isEmpty(s);
            if (temp) {
                break;
            } else {
                continue;
            }
        }
        return temp;
    }

    public static boolean isNotEmpty(String str) {
        boolean temp = false;
        if (null != str && !"".equals(str) && !"".equals(str.trim())
                && !"null".equals(str.trim())) {
            temp = true;
        }
        return temp;
    }

    public static String trim(String str) {
        String trimStr = "";
        if (null != str && !"".equals(str)) {
            trimStr = str.trim();
        }
        return trimStr;
    }

    public static boolean equals(String str, String str2) {
        if (isEmpty(str2) || isEmpty(str)) {
            return false;
        }
        return str.equals(str2);
    }

    private static MessageDigest digest = null;

    public synchronized static final String hash(String data) {
        if (digest == null) {
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException nsae) {

            }
        }
        // Now, compute hash.
        try {
            digest.update(data.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {

        }
        return encodeHex(digest.digest());
    }

    public static final String encodeHex(byte[] bytes) {
        StringBuffer buf = new StringBuffer(bytes.length * 2);
        int i;

        for (i = 0; i < bytes.length; i++) {
            if (((int) bytes[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString((int) bytes[i] & 0xff, 16));
        }
        return buf.toString();
    }

    /***
     * 获取request中的参数
     * @param request
     * @param removeSQLkey	是否移除sql关键字（面板查询中使用，导出excel不可用）
     * @return
     */
    public static Map<String,String> getParameterMap(HttpServletRequest request, boolean removeSQLkey) {
        Map<String,String> param = new HashMap<String,String>();
        StringBuilder sb = new StringBuilder();
        try{
            BufferedReader reader = request.getReader();
            char[]buff = new char[1024];
            int len;
            while((len = reader.read(buff)) != -1) {
                sb.append(buff,0, len);
            }
            param = getParamMap(sb);
        }catch (Exception e) {
            e.printStackTrace();
        }
        logger.info(sb);
        if(removeSQLkey){
            replaceSQLKeyWord(param);
        }
        return param;
    }


    /***
     * 移除sql关键字，避免sql注入
     */
    private static void replaceSQLKeyWord(Map<String,String> p){
        if(p != null && p.size() > 0){
            String v = "";
            for(Map.Entry<String, String> m : p.entrySet()){
                if(CommonTools.isNotEmpty(m.getValue())){
                    try {
                        v = m.getValue();
                        if(v.contains("'"))
                            v = v.replace("'", " ");
                        if(v.contains("\""))
                            v = v.replace("\"", " ");
                        if(v.contains("#"))
                            v = v.replace("#", " ");
                        if(v.contains("--"))
                            v = v.replace("--", " ");
                        if(v.contains("%"))
                            v = v.replace("%", " ");
                        m.setValue(v.trim());
                    }catch (Exception e){
                        System.out.println("Exception on replaceSQLKeyWord, key=" + m.getKey());
                    }
                }
            }
        }
    }

    private static Map<String,String> getParamMap(StringBuilder sb) throws Exception{
        Map<String,String> map = new HashMap<String,String>();
        String[] str = sb.toString().split("&");
        for(int i=0;i<str.length;i++){
            String[] lit = str[i].split("=");
            if(lit.length==1){
                map.put(URLDecoder.decode(lit[0],"UTF-8"),"");
            }else if(lit.length==2){
                map.put(URLDecoder.decode(lit[0],"UTF-8"),URLDecoder.decode(lit[1],"UTF-8"));
            }
        }
        return map;
    }
    public static boolean isNullOrEmpty(Object obj) {
        return obj == null || "".equals(obj.toString());
    }

    public static Object Decode(String json) {
        if (CommonTools.isNullOrEmpty(json)) return "";
        JSONDeserializer deserializer = new JSONDeserializer();
//		deserializer.use(String.class, new DateTransformer("yyyy-MM-dd'T'HH:mm:ss"));
        Object obj = deserializer.deserialize(json);
        if(obj != null && obj.getClass() == String.class){
            return Decode(obj.toString());
        }
        return obj;
    }

    /**
     * 实体对象转map
     * @param obj
     * @return
     */
    public static Map<String, Object> beanToMap(Object obj) {
        Map<String, Object> params = new HashMap<String, Object>(0);
        try {
            PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
            PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj);
            for (int i = 0; i < descriptors.length; i++) {
                String name = descriptors[i].getName();
                if (!"class".equals(name)) {
                    params.put(name, propertyUtilsBean.getNestedProperty(obj, name));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return params;
    }

    public static BigDecimal getBigDecimal(Object value ) {
        BigDecimal ret = null;
        if( value != null ) {
            if( value instanceof BigDecimal ) {
                ret = (BigDecimal) value;
            } else if( value instanceof String ) {
                ret = new BigDecimal( (String) value );
            } else if( value instanceof BigInteger) {
                ret = new BigDecimal( (BigInteger) value );
            } else if( value instanceof Number ) {
                ret = new BigDecimal( ((Number)value).doubleValue() );
            } else {
                throw new ClassCastException("Not possible to coerce ["+value+"] from class "+value.getClass()+" into a BigDecimal.");
            }
        }
        return ret;
    }

    /**
     * 发送Http请求 POST
     * @param url
     * @param param
     * @param secretKey
     * @return
     */
    public static ResultData getExchangeData(String url, Object param, String secretKey) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        MediaType mediaType = new MediaType("application", "json", Charsets.UTF_8);
        headers.setContentType(mediaType);
        headers.set("secretKey", secretKey);
        System.out.println(JSONObject.fromObject(param).toString());
        String jsonData = "";
        jsonData = JSONObject.fromObject(param).toString();
        RestTemplate ts = new RestTemplate();
        HttpEntity<String> entity = new HttpEntity<String>(jsonData, headers);
        ResponseEntity<ResultData> result = ts.exchange(url, HttpMethod.POST, entity, ResultData.class, "");
        ResultData res = result.getBody();
        return res;
    }

    /**
     * 发送Http请求 GET
     * @param url
     * @param secretKey
     * @return
     */
    public static ResultData httpGet(String url, String secretKey) {
        System.out.println("http:" + url);
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        MediaType mediaType = new MediaType("application", "json", StandardCharsets.UTF_8);
        headers.setContentType(mediaType);
        headers.set("secretKey", secretKey);
        HttpEntity<String> entity = new HttpEntity<String>("", headers);
        ResponseEntity<ResultData> result = restTemplate.exchange(url, HttpMethod.GET, entity, ResultData.class, "");
        return result.getBody();
    }

    /**\
     * 根据ｃｏｄｅ获取或者信息String
     */
    public static String  getExtString(RestTemplate rest,String code){
        ResultData<String> result = HttpUtil.httpGet_ResultData(ProConstants.getExtString+"?companyID="+ SystemContext.getCompanyID()+"&code="+code,rest);
        if(result.getData()==null){
            throw new ServiceException("根据编码"+code+"获取值失败", RestConst.ErrorCode.SERVICE_FAIL);
        }
        logger.info("根据编码获取 "+code+"  获取的值为  "+result.getData());
        return result.getData();
    }

}
